package cn.ycbjie.ycaudioplayer.newpack.linkagescroll;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.pedaily.yc.ycdialoglib.bottomLayout.BottomDialogFragment;
import com.pedaily.yc.ycdialoglib.customToast.ToastUtil;
import com.synjones.minnovate.frame.basesdk.http.SynHttp;
import com.synjones.minnovate.frame.basesdk.http.SynSchedulersTranfs;
import com.synjones.minnovate.frame.basesdk.http.exception.AbsRxSubscriber;
import com.synjones.minnovate.frame.basesdk.http.exception.ApiException;
import com.synjones.minnovate.frame.basesdk.log.SynLog;

import org.json.JSONArray;
import org.json.JSONObject;
import org.yczbj.ycrefreshviewlib.item.RecycleViewItemLine;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.ycbjie.ycaudioplayer.R;
import cn.ycbjie.ycaudioplayer.base.BaseAppHelper;
import cn.ycbjie.ycaudioplayer.executor.online.PlayOnlineMusic;
import cn.ycbjie.ycaudioplayer.inter.OnListItemClickListener;
import cn.ycbjie.ycaudioplayer.inter.OnPlayerEventListener;
import cn.ycbjie.ycaudioplayer.mybean.mycontent;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.RecyclerBaseAdapter2;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.RecyclerBaseAdapter3;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment3;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment3new;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.TabFragment;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.iapiserver.iapi;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.mybeans.MyPlayerlistBean;
import cn.ycbjie.ycaudioplayer.service.PlayService;
import cn.ycbjie.ycaudioplayer.ui.guide.contract.GuideContract;
import cn.ycbjie.ycaudioplayer.ui.main.MainHomeActivity;
import cn.ycbjie.ycaudioplayer.ui.music.local.model.AudioMusic;
import cn.ycbjie.ycaudioplayer.ui.music.local.view.DialogMusicListAdapter;
import cn.ycbjie.ycaudioplayer.ui.music.local.view.DialogOLMusicListAdapter;
import cn.ycbjie.ycaudioplayer.ui.music.onLine.model.bean.OnlineMusicList;
import cn.ycbjie.ycaudioplayer.util.musicUtils.CoverLoader;

import static cn.ycbjie.ycaudioplayer.newpack.linkagescroll.config.MyConfig.baseURL;

/**
 * Created by yuyu on 2018-12-07.
 */

public class MyPlayerActivity extends AppCompatActivity {


    private static final String TAG = "myplayeractivity";
    ImageView ivPlayBarCover;
    TextView tvPlayBarTitle;
    TextView tvPlayBarArtist;
    ImageView ivPlayBarPlay,iv_play_bar_list;
    ProgressBar pbPlayBar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private WebView webView;


    private String ids;
    private String listid;
    private String pics;
    private String titles;
    private long du;
    private boolean mIsLoading;
    protected List<mycontent> dataList = new ArrayList<>();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nest_playeractivity);

        ids = getIntent().getStringExtra("ids");
        listid = getIntent().getStringExtra("listid");
        titles = getIntent().getStringExtra("title");
        pics = getIntent().getStringExtra("pic");
        du = getIntent().getLongExtra("du",0)*1000;
        intview();
        intliser();
        intdata();
        playbyid(0,true);
    }

    private void intview()
    {
        View view = findViewById(R.id.in_playbar);
        ivPlayBarCover =(ImageView)view.findViewById(R.id.iv_play_bar_cover);
        tvPlayBarTitle = (TextView)view.findViewById(R.id.tv_play_bar_title);
        tvPlayBarArtist = (TextView)view.findViewById(R.id.tv_play_bar_artist);
        ivPlayBarPlay = (ImageView)view.findViewById(R.id.iv_play_bar_play);
        pbPlayBar= (ProgressBar)view.findViewById(R.id.pb_play_bar);
        iv_play_bar_list=(ImageView)view.findViewById(R.id.iv_play_bar_list);
        viewPager = findViewById(R.id.data_pager);
        tabLayout = findViewById(R.id.tab_layout);

      webView = (WebView)findViewById(R.id.web_tow);
//        webView.loadUrl("file:///android_asset/test.html");//加载asset文件夹下html
//        webView.loadUrl("http://www.baidu.com");//加载url
    }

    private void getplayererlist(String id) {

        SynHttp.getInstance().getApi(baseURL, iapi.class).getContent(id)
                .compose(SynSchedulersTranfs.<mycontent>schedulersTransformer())
                .subscribe(new AbsRxSubscriber<mycontent>() {
                    @Override
                    public void onRxError(ApiException ex) {
                        SynLog.file(ex.getDisplayMessage());
                    }


                    public void onNext(mycontent mymycontent) {
                        dataList.add(mymycontent);
                        try {
                            webView.loadData(getHtmlData(mymycontent.getData().getContent()), "text/html;charset=utf-8", "utf-8");

//                            if (recyclerBaseAdapter2 != null) {
//                                recyclerBaseAdapter2.notifyDataSetChanged();
//                            }
//                            recyclerBaseAdapter2 = new RecyclerBaseAdapter2(getActivity(), dataList);
//                            listItemRecycler.setAdapter(recyclerBaseAdapter2);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
//                            SynLog.file("String----->" + weatherInfoBean.toString());
                    }
                });

    }
    private void intdata()
    {
        viewPager.setAdapter(new MyPlayerActivity.TabAdapter(getSupportFragmentManager()));
        viewPager.setOffscreenPageLimit(1);
        tabLayout.setupWithViewPager(viewPager);
        getplayererlist(listid);


    WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        webView.setWebViewClient(new MyWebViewClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
    } else {
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    }
        if (webView.isHardwareAccelerated()) settings.setJavaScriptEnabled(true);
//        webView.setWebViewClient(new WebViewClient());
//        webView.setWebChromeClient(new WebChromeClient());
//        WebSettings settings = webView.getSettings();
//        settings.setJavaScriptEnabled(true);
//        webView.loadUrl("https://www.jianshu.com/c/fcd7a62be697?utm_source=mobile&utm_medium=collections");


//        webView = (WebView)v.findViewById(R.id.web);
//
//        WebSettings webSettings = webView.getSettings();
////支持缩放，默认为true。
//        webSettings .setSupportZoom(false);
////调整图片至适合webview的大小
//        webSettings .setUseWideViewPort(true);
//// 缩放至屏幕的大小
//        webSettings .setLoadWithOverviewMode(true);
////设置默认编码
//        webSettings .setDefaultTextEncodingName("utf-8");
//////设置自动加载图片
//        webSettings .setLoadsImagesAutomatically(true);
//        webView.loadUrl("https://www.jianshu.com/c/fcd7a62be697?utm_source=mobile&utm_medium=collections");
//        return holder;

}

    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>html{padding:15px;} body{word-wrap:break-word;font-size:13px;padding:0px;margin:0px} p{padding:0px;margin:0px;font-size:13px;color:#222222;line-height:1.3;} img{padding:0px,margin:0px;max-width:100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //判断重定向的方式一
//            WebView.HitTestResult hitTestResult = view.getHitTestResult();
//            if(hitTestResult == null) {
//                return false;
//            }
//            if(hitTestResult.getType() == WebView.HitTestResult.UNKNOWN_TYPE) {
//                return false;
//            }

            //判断重定向的方式二
            if(mIsLoading) {
                return false;
            }

            if(url != null && url.startsWith("http")) {
                webView.loadUrl(url);
                return true;
            } else {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    view.getContext().startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                return true;
            }
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mIsLoading = true;
            Log.d(TAG, "onPageStarted");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mIsLoading = false;
            Log.d(TAG, "onPageFinished");
        }

//        @Override
//        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//            super.onReceivedError(view, request, error);
//        }
    }


    private class TabAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragmentList = new ArrayList<>();
        private List<String> tabList = new ArrayList<>();
        public TabAdapter(FragmentManager fm) {
            super(fm);
//            TabFragment listFragment1 = new TabFragment("",MyPlayerActivity.this);
//            TabFragment listFragment2 = new TabFragment("",MyPlayerActivity.this);
            ListFragment3new listFragment3 = new ListFragment3new("jneu340d95do");
//            TabFragment tabFragment = new TabFragment();
//            fragmentList.add(listFragment1);
//            tabList.add("详情");
//            fragmentList.add(listFragment2);
//            tabList.add("列表");
            fragmentList.add(listFragment3);
            tabList.add("");
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
//            return  new TabFragment();
        }

        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabList.get(position);
        }
    }

    private void intliser()
    {
        ivPlayBarPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPlayService().playPause();
                onChangeImpl(getPlayService().getPlayingMusic());
            }
        });
        ivPlayBarPlay.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Log.d("ACETEST", "监听");
            return true;
        }
    });
        iv_play_bar_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getplayererlist(listid,"10","1",true);

            }
        });

        initPlayServiceListener();
    }

    private void playbyid(final int position, final boolean isdian) {
        String id = ids;
        final String pic =pics;
        final String title =titles;
        SynHttp.getInstance().getApi(baseURL, iapi.class).getmp3(id,"")
                .compose(SynSchedulersTranfs.<String>schedulersTransformer())
                .subscribe(new AbsRxSubscriber<String>() {
                    @Override
                    public void onRxError(ApiException ex) {
                        SynLog.file(ex.getDisplayMessage());
                    }

                    public void onNext(String weatherInfoBean) {

                        try {
                            JSONObject obj = new JSONObject(weatherInfoBean.toString());
                            String code = obj.getString("code");
                            if("200".equalsIgnoreCase(code)) {
                                String data = obj.getString("data");

                                JSONObject objer = new JSONObject(data);

                                String uri = objer.getString("uri");
                                if (uri != null && !"".equals(uri)) {
                                    if (!isdian) {
//                                        smoothMoveToPosition(listItemRecycler, Integer.valueOf(position));
//                                        recyclerBaseAdapter.setDefSelect(Integer.valueOf(position));
                                    }
                                    AudioMusic audioMusic = new AudioMusic();
                                    audioMusic.setArtist(title);
                                    audioMusic.setCoverPath(pic);
                                    audioMusic.setPath(uri);
                                    audioMusic.setDuration(du);
                                    audioMusic.setTitle(title);
                                    getPlayService().play(audioMusic, position);
                                } else {
                                    getPlayService().stop();
                                    Toast.makeText(MyPlayerActivity.this, "没有播放权限", Toast.LENGTH_SHORT).show();
                                }
                            }
                            else
                            {
                                getPlayService().stop();
                                Toast.makeText(MyPlayerActivity.this, "没有播放权限", Toast.LENGTH_SHORT).show();
                            }
                            onChangeImpl(getPlayService().getPlayingMusic());

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        SynLog.file("String----->" + weatherInfoBean.toString());
                    }
                });
    }
    /**
     * 初始化服务播放音频播放进度监听器
     * 这个是要是通过监听即时更新主页面的底部控制器视图
     * 同时还要同步播放详情页面mPlayFragment的视图
     */
    public void initPlayServiceListener() {
        if (getPlayService() == null) {
            return;
        }
        getPlayService().setOnPlayEventListener(new OnPlayerEventListener() {
            /**
             * 切换歌曲
             * 主要是切换歌曲的时候需要及时刷新界面信息
             */
            @Override
            public void onChange(AudioMusic music) {
                onChangeImpl(music);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onChange(music);
//                }
            }

            /**
             * 继续播放
             * 主要是切换歌曲的时候需要及时刷新界面信息，比如播放暂停按钮
             */
            @Override
            public void onPlayerStart() {
                ivPlayBarPlay.setSelected(true);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onPlayerStart();
//                }
            }

            /**
             * 暂停播放
             * 主要是切换歌曲的时候需要及时刷新界面信息，比如播放暂停按钮
             */
            @Override
            public void onPlayerPause() {
                ivPlayBarPlay.setSelected(false);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onPlayerPause();
//                }
            }

            /**
             * 更新进度
             * 主要是播放音乐或者拖动进度条时，需要更新进度
             */
            @Override
            public void onUpdateProgress(int progress) {
                pbPlayBar.setProgress(progress);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onUpdateProgress(progress);
//                }
            }

            @Override
            public void onBufferingUpdate(int percent) {
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onBufferingUpdate(percent);
//                }
            }

            /**
             * 更新定时停止播放时间
             */
            @Override
            public void onTimer(long remain) {

            }
        });
    }
    public PlayService getPlayService() {
        PlayService playService = BaseAppHelper.get().getPlayService();
        if (playService == null) {
            throw new NullPointerException("play service is null");
        }
        return playService;
    }

    private void playMusic(OnlineMusicList.OnlineMusic onlineMusic) {
        new PlayOnlineMusic(MyPlayerActivity.this, onlineMusic) {
            @Override
            public void onPrepare() {
            }

            @Override
            public void onExecuteSuccess(AudioMusic music) {
                getPlayService().play(music);
                ToastUtils.showShort("正在播放" + music.getTitle());

            }

            @Override
            public void onExecuteFail(Exception e) {
                ToastUtils.showShort(R.string.unable_to_play);
            }

        }.execute();
    }

    public void onChangeImpl(AudioMusic music) {
        if (music == null) {
            return;
        }
//        Bitmap cover = CoverLoader.getInstance().loadThumbnail(music);

        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.default_cover);
        Glide.with(this)
                .load(music.getCoverPath())
                .apply(options)
                .into(ivPlayBarCover);

/*圆图
        Glide.with(this).load(music.getCoverPath()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(ivPlayBarCover);
*/




//        ivPlayBarCover.setImageBitmap(cover);
        tvPlayBarTitle.setText(music.getTitle());
        tvPlayBarArtist.setText(music.getArtist());
        boolean isplaying = getPlayService().isPlaying();
        boolean ispre = getPlayService().isPreparing();
        boolean isdef = getPlayService().isDefault();

        ivPlayBarPlay.setSelected(getPlayService().isPlaying() || getPlayService().isPreparing());
        //更新进度条
        pbPlayBar.setMax((int) music.getDuration());
        pbPlayBar.setProgress((int) getPlayService().getCurrentPosition());

    }


    private void getplayererlist(String id, final String limit, final String page, final Boolean isfirst) {

        final ArrayList<MyPlayerlistBean> lcs = new ArrayList<MyPlayerlistBean>();
        final ArrayList<OnlineMusicList.OnlineMusic> listmusic = new ArrayList<OnlineMusicList.OnlineMusic>();
        SynHttp.getInstance().getApi(baseURL, iapi.class).getListmp3(id, limit, page)
                .compose(SynSchedulersTranfs.<String>schedulersTransformer())
                .subscribe(new AbsRxSubscriber<String>() {
                    @Override
                    public void onRxError(ApiException ex) {
                        SynLog.file(ex.getDisplayMessage());
                    }


                    public void onNext(String weatherInfoBean) {
                        try {
                            JSONObject obj = new JSONObject(weatherInfoBean.toString());
                            String code = obj.getString("code");
                            String data = obj.getString("data");

                            JSONObject objer = new JSONObject(data);
                            JSONArray jsonArray = objer.getJSONArray("data");
                            String dataer = objer.getString("data");
                            int total = Integer.parseInt(objer.getString("total"));
                            int limit = 100;//Integer.parseInt(objer.getString("limit"));
                            int pp = total / limit + 1;
                            Gson gson = new Gson();
                            JsonParser parser = new JsonParser();
                            JsonArray Jarray = parser.parse(dataer).getAsJsonArray();
                            int i = 0;
                            for (JsonElement objel : Jarray) {
                                MyPlayerlistBean cse = gson.fromJson(objel, MyPlayerlistBean.class);
                                lcs.add(cse);
if(lcs.get(i).isTrial()) {
    OnlineMusicList.OnlineMusic onlineMusic = new OnlineMusicList.OnlineMusic();
    onlineMusic.setTitle(lcs.get(i).getTitle());
    onlineMusic.setSong_id(lcs.get(i).getId());
    onlineMusic.setPic_big(lcs.get(i).getCover());
    listmusic.add(onlineMusic);
}
                                i++;

                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        SynLog.file("String----->" + weatherInfoBean.toString());
                        showListDialog(listmusic);
                    }
                });
    }

    public void showListDialog(final List<OnlineMusicList.OnlineMusic> musicLists) {
//        getplayererlist(listid,"10","1",true);
        final List<OnlineMusicList.OnlineMusic> musicList =musicLists;// getplayererlist(listid,"10","1",true);//BaseAppHelper.get().getMusicList();
       Log.e("list------------",musicList.size()+"");
        final BottomDialogFragment dialog = new BottomDialogFragment();
        dialog.setFragmentManager(getSupportFragmentManager());
        dialog.setViewListener(new BottomDialogFragment.ViewListener() {
            @Override
            public void bindView(View v) {
                RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
                TextView tvPlayType = (TextView) v.findViewById(R.id.tv_play_type);
                TextView tvCollect = (TextView) v.findViewById(R.id.tv_collect);
                ImageView ivClose = (ImageView) v.findViewById(R.id.iv_close);

                recyclerView.setLayoutManager(new LinearLayoutManager(MyPlayerActivity.this));
                final DialogOLMusicListAdapter mAdapter = new DialogOLMusicListAdapter(MyPlayerActivity.this, musicList);
                recyclerView.setAdapter(mAdapter);
                mAdapter.updatePlayingPosition(getPlayService());
                final RecycleViewItemLine line = new RecycleViewItemLine(MyPlayerActivity.this, LinearLayout.HORIZONTAL,
                        SizeUtils.dp2px(1), MyPlayerActivity.this.getResources().getColor(R.color.grayLine));
                recyclerView.addItemDecoration(line);
                mAdapter.setOnItemClickListener(new OnListItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        List<AudioMusic> musicList = BaseAppHelper.get().getMusicList();
                        getPlayService().play(musicList,position);
                        mAdapter.updatePlayingPosition(getPlayService());
                        mAdapter.notifyDataSetChanged();
                    }
                });
                View.OnClickListener listener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.tv_play_type:

                                break;
                            case R.id.tv_collect:
                                ToastUtil.showToast(MyPlayerActivity.this, "收藏，后期在做");
                                break;
                            case R.id.iv_close:
                                dialog.dismissDialogFragment();
                                break;
                            default:
                                break;
                        }
                    }
                };
                tvPlayType.setOnClickListener(listener);
                tvCollect.setOnClickListener(listener);
                ivClose.setOnClickListener(listener);
            }
        });
        dialog.setLayoutRes(R.layout.dialog_bottom_list_view);
        dialog.setDimAmount(0.5f);
        dialog.setTag("BottomDialogFragment");
        dialog.setCancelOutside(true);
        //这个高度可以自己设置，十分灵活
        dialog.setHeight(ScreenUtils.getScreenHeight() * 6 / 10);
        dialog.show();
    }
}
